<template>
  <div class="app-container">
      <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>经销商分润列表</span><span class="warm-tip">(当前页面的金额单位为 {{moneyIcon}})</span>
      <!-- <el-button class="btn-add" @click="handleAddProduct()" size="mini">
        添加新经销商
      </el-button> -->
      <a :href="exportSumExcel" class="btn-add margin" target="_blank"><el-button type="primary" size="medium" plain>导出所有分销商分润信息</el-button></a>
    </el-card>
    <el-table ref="productTable"
          :data="list"
          style="width: 100%;margin-bottom: 20px;"
          v-loading="listLoading"
          row-key="id"
          border
          :row-class-name="tableRowClassName"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          >
        <!-- <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope"> {{scope.row.id}} </template>
        </el-table-column> -->
         <el-table-column label="经销商ID" width="100" align="center">
          <template slot-scope="scope"> {{scope.row.distributorId}} </template>
        </el-table-column>
        <el-table-column label="经销商姓名" width="150" align="center">
          <template slot-scope="scope"> {{scope.row.username}} </template>
        </el-table-column>
        <!-- <el-table-column label="统计月份" width="200" align="center">
          <template slot-scope="scope">{{scope.row.recordMonth}}</template>
        </el-table-column> -->
        <el-table-column label="总销售额" width="100" align="center">
          <template slot-scope="scope">{{scope.row.totalAmount }}</template>
        </el-table-column>
        <el-table-column label="可分红" width="100" align="center">
          <template slot-scope="scope">{{scope.row.canBonusAmount}}</template>
        </el-table-column>
         <el-table-column label="待分红" width="100" align="center">
          <template slot-scope="scope">{{scope.row.waitBonusAmount}}</template>
        </el-table-column>
         <el-table-column label="已分红" width="100" align="center">
          <template slot-scope="scope">{{scope.row.hasBonusAmount}}</template>
        </el-table-column>
        <!-- <el-table-column label="是否已分红" width="100" align="center">
          <template slot-scope="scope">
            {{scope.row.status ==0?'未分红':'已分红'}}
          </template>
        </el-table-column> -->
        <el-table-column label="操作"  align="center">
          <template slot-scope="scope">
              <!-- <el-button
                size="mini"
                @click="downloadSingleSalesman(scope.$index, scope.row)">导出明细
              </el-button> -->
              <a :href="exportSingleExcel+scope.row.distributorId" class="btn-add margin" target="_blank"><el-button type="primary" size="mini">导出明细</el-button></a>
              <el-button
                size="mini"
                type="danger"
                @click="confirmHasGived(scope.$index, scope.row)">确认打款
              </el-button>
          </template>
        </el-table-column>
    </el-table>
    <!-- 经销商推广订单列表 -->
    <el-dialog title="经销商推广订单列表" width="34rem" :visible.sync="ispromotionOrderListOpen" :close-on-click-modal="true" :show-close="true" class="adjustmentBox">
      <el-table :data="promotionOrderList" border style="width: 100%;margin-bottom: 20px;">
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope"> {{scope.row.id}} </template>
        </el-table-column>
         <el-table-column label="订单号" width="100" align="center">
          <template slot-scope="scope"> {{scope.row.orderId}} </template>
        </el-table-column>
        <el-table-column label="订单金额" width="150" align="center">
          <template slot-scope="scope"> {{scope.row.orderAmount}} </template>
        </el-table-column>
        <el-table-column label="统计日期"  align="center">
          <template slot-scope="scope"> {{scope.row.recordDate}} </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
    import {
    fetchSalesmanProfitList,
    updateSalesmanProfitInfo,
    getSalesmanProfitList,
    operateSalesmanProfigDetail,
    getSalesmanProfigDetail,
  } from '@/api/salesprofit'
  import {getUnredMessageSum} from '@/utils/index';
//   import {fetchList as fetchSkuStockList,update as updateSkuStockList} from '@/api/skuStock'
//   import {fetchList as fetchProductAttrList} from '@/api/productAttr'
//   import {fetchList as fetchBrandList} from '@/api/brand'
//   import {fetchListWithChildren} from '@/api/productCate'

  const defaultListQuery = {
    // nickname: null,
    pageNum: 1,
    pageSize: 5,
  };
  export default {
    name: "SalesmanList",
    data() {
      return {
        highlightId:0,//高亮显示的行
        exportSumExcel: process.env.BASE_API + 'admin/distributor/export/distributor/bonus/info',//所有的，不传参
        exportSingleExcel: process.env.BASE_API + 'admin/distributor/export/distributor/bonus/info?did=',//单个导出，要传参
        moneyIcon:process.env.MONEY_ICON,
        promotionOrderList:[],//某经销商推广订单列表
        ispromotionOrderListOpen:false,//某经销商推广订单列表弹窗
          list:[],
          defaultProps: {
            children: 'children',
            label: 'label'
            },
          listQuery:Object.assign({}, defaultListQuery),
          newForm:{//新增经销商弹框里内容
            nickname:'',
            invitationCode:'',
            desc:'',
            status:1,
          },
          editForm: {//编辑经销商弹框里内容
            nickname:'',
            invitationCode:'',
            desc:'',
            multipleSelection:[],
            status:1,
          },
          promotionList:{
            list:[],
            listQuery:{
              keyword: null,
              pageNum: 1,
              pageSize: 5,
            },
            total:null,
          },
          newFormRules:{
            nickname:[
                { required: true,  message: '经销商名不能为空', trigger: ['blur','change']}
             ],
            invitationCode:[
                { required: true,  message: '链接不能为空', trigger: ['blur','change']}
             ],
            //  sort:[
            //     { required: true,  message: '排序不能为空', trigger: ['blur','change']}
            //  ],
            //  icon:[
            //     { required: true,  message: '图标不能为空', trigger: ['blur','change']}
            //  ],
          },
          editFormRules:{
            nickname:[
                { required: true,  message: '经销商名不能为空', trigger: ['blur','change']}
             ],
             invitationCode:[
                { required: true,  message: '链接不能为空', trigger: ['blur','change']}
             ],
            //  sort:[
            //     { required: true,  message: '排序不能为空', trigger: ['blur','change']}
            //  ],
            //  icon:[
            //     { required: true,  message: '图标不能为空', trigger: ['blur','change']}
            //  ],
          },

          isNewSalesmanOpen:false,//新增经销商弹窗
          isEditSalesmanOpen:false,//编辑经销商弹窗
         
      }
    },
    created() {
      this.getList();
      if(this.$route.query.selectid){
        this.highlightId = this.$route.query.selectid
      }
      this.getUnreadMsg();
    },
    methods:{
      getUnreadMsg(){
        getUnredMessageSum().then((res)=>{
          if(res &&res.data>=0){
            this.$store.dispatch("RefreshUnreadMsgSum",res.data)
          }
        })
      },
      tableRowClassName({row, rowIndex}) {
        if (row.distributorId == this.highlightId) {
          return 'warning-row';
        } 
        return '';
      },
      //确认打款
      confirmHasGived(index,row){
        getSalesmanProfigDetail(row.distributorId).then(response => {
          if(response.code === 200){
              // this.listLoading = false;
              // let res = response.data;
              // this.list = res.orderList;
              // this.currentProfitInfo = res;
            return response.data
          }
        }).then(info=>{
          // console.log(info);
          if(!info){
            this.$message({
               message: '当前用户尚未绑定提现账户信息！',
              type: 'warning',
              duration: 2000
            })
            return;
          }
            let name = info.username,
            phone = info.phone,
            alipay = info.payAccount,
            money = info.canBonusAmount;

        this.$confirm('<div><h4>请确认以下提现信息</h4><p>姓名：'+name+'</p><p>手机号：'+phone+'</p><p>支付宝账号：'+alipay+'</p><p>可提现金额：'+this.moneyIcon+money+'</p></div>', '提示：此操作不可逆', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
              let did = row.distributorId;
              let orderSn = row.orderSn;
              console.log(orderSn);
              // return
              operateSalesmanProfigDetail(did,{distributorId:did,orderSns:orderSn}).then(res=>{
                  if(res.code ==200){
                      this.$message({
                          message: '操作成功',
                          type: 'success',
                          duration: 2000
                      });
                      this.getList();
                  }else{
                      this.$message({
                          message: res.message?res.message:'操作失败',
                          type: 'error',
                          duration: 2000
                      })
                  }
              })
            })
        })

        
      },
      //导出单个经销商的数据明细
      downloadSingleSalesman(){

      },
      getList() {
        this.listLoading = true;
        fetchSalesmanProfitList(this.listQuery).then(response => {
            if(response.code === 200){
               this.listLoading = false;
                let res = response.data;
                this.list = res;
                //this.list = res.list;
                // this.total = response.data.total;
                // this.totalPage = response.data.totalPage;
                // this.pageSize = response.data.pageSize;
            }
        });
      },
      searchQueryList(){
        this.listQuery.pageNum = 1;
        this.getList();
      },
      getSalesmanProfitListFun(index,row){
        this.$router.push({path:'/ums/salesprofitdetail',query:{id:row.distributorId,orderSn:row.orderSn}});
        // let tempObj={};
        // tempObj.distributorId = row.distributorId;
        // tempObj.recordMonth = row.recordMonth;
        // // tempObj.startDate='2020-03-01';
        // // tempObj.endDate='2020-03-31';
        // tempObj.pageNum = 1;
        // tempObj.pageSize=1000;
        // getSalesmanProfitList(tempObj).then(res=>{
        //   if(res.code ==200){
        //     this.promotionOrderList = res.data;
        //     this.ispromotionOrderListOpen = true;
        //   }
        // })
      },
      showupdateSalesmanProfitInfo(index,row){
        let self = this;
        let tempStatus = row.status;
        if(tempStatus==1){
          self.$message({
             message: '已分红状态不允许修改',
              type: 'error',
              duration: 2000
          });
          return
        }
        let tempStatusTxt = '';
        if(tempStatus==0){
          tempStatusTxt='已分红'
        }else{
          tempStatusTxt='未分红'
        }
        this.$confirm('是否将状态更新为'+tempStatusTxt, '提示：此操作不可逆', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateSalesmanProfitInfo(row.id).then(res=>{
            if(res.code ==200){
              self.$message({
                message: '更新成功',
                type: 'success',
                duration: 1000
              })
              self.getList();
            }
          })
        })
      },
      // updateSalesmanProfitInfo(index,item){
      //   let self = this;
      //   self.editForm = Object.assign(self.editForm,JSON.parse(JSON.stringify(item)));
      //   self.editForm.currentUId = item.id;
      //   if(item.discountId){
      //     let row=null;
      //     let curPId= item.discountId;
      //     self.promotionList.list.forEach((item,index)=>{
      //       if(item.id == curPId){
      //         row = item;
      //         //self.handleSelectionChange(row);
      //         console.log(row);
      //         self.$refs['singleTable'].setCurrentRow(row)
      //       }
      //     })
          
      //   }
      // },
      getPromotionList(){
        fetchSalesDiscountList().then(res=>{
          this.promotionList.list = res.data.list;
          this.promotionList.total = res.data.list.total;
        })
      },
      handleSelectionChange(val){
        console.log(val);
        this.editForm.multipleSelection = val;
      },
      handleAddProduct(){
          this.isNewSalesmanOpen = true;
      },
      saveNewSalesman(){
          let self= this;
          self.newForm.description = self.newForm.name;
          console.log(self.newForm);
        newSalesmanInfo(self.newForm).then(response=>{
            if(response.code == 200){
                self.$message({
                message: '新建成功',
                type: 'success',
                duration: 1000
            });
            self.isNewSalesmanOpen=false;
            self.getList();
            }
        })
      },
    //   saveSalesmanInfo(){
    //       console.log(this.editForm);
    //     this.editForm.discountId = this.editForm.multipleSelection.id;
    //     updateSalesmanProfitInfo(this.editForm.currentUId,this.editForm).then(response=>{
    //         this.$message({
    //             message: '修改成功',
    //             type: 'success',
    //             duration: 1000
    //         });
    //         this.isEditSalesmanOpen=false;
    //         this.getList();
    //     });
    //   },
       handleDialogSizeChange(val) {
        this.editForm.listQuery.pageNum = 1;
        this.editForm.listQuery.pageSize = val;
        this.getPromotionList();
      },
      handleDialogCurrentChange(val) {
        this.editForm.listQuery.pageNum = val;
        this.getPromotionList();
      },
      handleDeleteSalesman(index,item){
          let self = this;
           self.$confirm('删除该经销商, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                // let arrTemp= [];
                // arrTemp.push(item.id);
                // //objTemp.ids = arrTemp;
                // let params = new URLSearchParams();
                // params.append('id', arrTemp);
                let delId=item.id;
                deleteSalesman(delId).then(response=>{
                    if(response.code === 200){
                        self.$message({
                            message: '删除成功',
                            type: 'success',
                            duration: 1000
                        });
                        self.getList();
                    }
                });
            }).catch(() => {
                // self.$message({
                //     type: 'info',
                //     message: '已取消删除'
                // });          
            });
      },
      
    }
  }
</script>
<style scoped>
   .app-container >>> .warning-row {
    background: #f0f9eb;
   }
.btn-add{
    font-size: 14px;
    padding: 10px;
    margin-top: -8px;
  color:#fff;
  /* background-color:#417FF6; */
}
/* 弹出框的宽度 */
.adjustmentBox >>> .el-dialog{
  width: 28rem;
} 

.editform-promotion >>> tr.current-row td{
  background-color: #999;
}
</style>